﻿//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App
{
    using System;
    using System.Diagnostics;
    using System.Windows.Forms;
    using App.Jobs.AppStartup;
    using App.UI;
    using TileTool.Base.Log;
    using TileTool.Base.Threading.Job;
    using TileTool.Log;
    using TileTool.Threading.Future;
    using TileTool.Threading.Job;

    /// <summary>
    /// Tile tool application entry point.
    /// </summary>
    public static class Program
    {
        #region Constants

        /// <summary>
        /// Max job count the application supports.
        /// </summary>
        private const int MaxJobCount = 8;

        /// <summary>
        /// Timer interval in MS.
        /// </summary>
        private const int TimerIntervalMS = 1000 / 24;

        #endregion

        #region Fields - Private

        /// <summary>
        /// Application splash screen.
        /// </summary>
        private static SplashScreenForm splash;

        /// <summary>
        /// Application context we use to control lifetime of the application.
        /// </summary>
        private static ApplicationContext applicationContext = new ApplicationContext();

        /// <summary>
        /// Main application.
        /// </summary>
        private static TileToolApplication application;

        /// <summary>
        /// Work timer.
        /// </summary>
        private static Timer workTimer;

        #endregion

        #region Methods - Public

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            SetupCriticalSystems();
            ShowSplashScreen();

            application = new TileToolApplication();
            AppStartupJob startupJob = new AppStartupJob(application);

            startupJob.Future.OnComplete(OnStartupComplete);

            JobSystem.Submit(startupJob);

            Application.Run(applicationContext);

            if (workTimer != null)
            {
                workTimer.Stop();
                workTimer.Dispose();
            }

            application.Shutdown();
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Function used to setup all application critical systems.
        /// </summary>
        private static void SetupCriticalSystems()
        {
            LogSystem.Manager = new LogManager();
            LogSystem.AddOutputTarget(new DebugOutputLogOutputTarget());

            JobSystem.Manager = new JobManager(MaxJobCount);
        }

        /// <summary>
        /// Show the application startup splash screen.
        /// </summary>
        private static void ShowSplashScreen()
        {
            Debug.Assert(splash == null, "Splash screen should always be null here.");
            splash = new SplashScreenForm();
            splash.Show();
        }

        /// <summary>
        /// Close the splash screen.
        /// </summary>
        private static void CloseSplashScreen()
        {
            splash.Close();
            splash = null;
        }

        /// <summary>
        /// Application startup has completed, so launch the application by showing its
        /// main form and setting up the idle loop.
        /// </summary>
        private static void LaunchApplication()
        {
            Form mainForm = application.CreateMainWindow();

            applicationContext.MainForm = mainForm;

            mainForm.Show();

            workTimer = new Timer();
            workTimer.Tick += (object sender, EventArgs e) => HandleApplicationWork();
            workTimer.Interval = TimerIntervalMS;
            workTimer.Start();
        }

        /// <summary>
        /// Triggered when the application is idle.
        /// </summary>
        private static void HandleApplicationWork()
        {
            application.Work();
        }

        /// <summary>
        /// Called when the application startup job completes.
        /// </summary>
        /// <param name="future">Future object that just completed.</param>
        private static void OnStartupComplete(IFuture future)
        {
            CloseSplashScreen();

            if (future.IsCompleted)
            {
                LaunchApplication();
            }
            else if (future.IsCanceled)
            {
                MessageBox.Show("Startup task canceled.", "Error", MessageBoxButtons.OK);

                applicationContext.ExitThread();
            }
            else
            {
                Debug.Assert(future.IsError, "Must be an error in this case.");

                MessageBox.Show(future.Error.Message, "Error", MessageBoxButtons.OK);

                applicationContext.ExitThread();
            }
        }

        #endregion
    }
}
